/**
 * <br>项目名: fastdfs-api
 * <br>文件名: UploadCtrl.java
 * <br>Copyright 2015 恒昌互联网运营中心
 */
import org.apache.http.Consts;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.CharsetUtils;
import org.apache.http.util.EntityUtils;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.nio.charset.Charset;
import java.util.Date;
/**
 * @ClassName: NewTestUpload
 * @Description: 文件上传下载
 * @author zhaoc
 * @date 2015年6月17日
 * @time  上午11:02:22
 */
public class NewTestUpload {
	private Logger log = LoggerFactory.getLogger(NewTestUpload.class);

	private static String UPLOAD_PATH;
	private static String DOWNLOAD_PATH;

	static {
//		UPLOAD_PATH = "http://172.19.0.146/fs-api/uploadFile.hc";//预发布
//		UPLOAD_PATH = "http://192.168.100.70/fs-api/uploadFile.hc";/*测试环境*/
//		DOWNLOAD_PATH = "http://filesys-test.hengchang6.com/fs-api/downloadFile.hc";/*测试环境*/
//		DOWNLOAD_PATH = "http://192.168.100.70/fs-api/downloadFile.hc";/*测试环境*/
		//工单系统,实际为192.168.100.70
		//UPLOAD_PATH = "http://111.204.230.5:18080/fs-api/uploadFile.hc";

		//UPLOAD_PATH = "http://118.26.169.228/fs-api/uploadFile.hc";//生产环境
		UPLOAD_PATH = "http://10.160.13.128/fs-api/uploadFile.hc";//新测试环境
	}

	private static class SingleHolder {
		static final NewTestUpload instance = new NewTestUpload();
	}

	public static NewTestUpload getInstance() {
		return SingleHolder.instance;
	}

	/**
	 * @Title: upload
	 * @Description: 文件上传
	 * @param
	 * @return void
	 * @throws
	 */
	@Test
	public void upload() throws Exception {
    	CloseableHttpClient httpClient = HttpClients.createDefault();
        try {
            // 要上传的文件的路径
            String filePath = "/Users/zhangjin/temp/fav.png";
            // 把一个普通参数和文件上传给下面这个地址 是一个servlet
            HttpPost httpPost = new HttpPost(UPLOAD_PATH);
            // 把文件转换成流对象FileBody
            File file = new File(filePath);
            FileBody bin = new FileBody(file);
            //调用者业务ID
            StringBody businessId = new StringBody("200", ContentType.create("text/plain", Consts.UTF_8));
            //调用者系统ID
            StringBody systemId = new StringBody("dsjbdp", ContentType.create("text/plain", Consts.UTF_8));
            //文件类型(注* 此处上传pdf类型文件，fileType参数填写为 doc)
            StringBody fileType = new StringBody("img", ContentType.create("text/plain", Consts.UTF_8));
            //文件原始名称
            StringBody fileName = new StringBody("fav.png", ContentType.create("text/plain", Consts.UTF_8));
            //从文件名，非图片类型不需要裁剪 缩放的文件 此参数为空
            StringBody slaveName = new StringBody("", ContentType.create("text/plain", Consts.UTF_8));
            //以浏览器兼容模式运行，防止文件名乱码。
            HttpEntity reqEntity = MultipartEntityBuilder.create().setMode(HttpMultipartMode.BROWSER_COMPATIBLE)
                    .addPart("file", bin)
                    .addPart("systemId", systemId)
                    .addPart("fileType", fileType)
                    .addPart("fileName", fileName)
                    .addPart("slaveName", slaveName)
                    .addPart("businessId", businessId).setCharset(CharsetUtils.get("UTF-8")).build();//请求编码使用UTF-8

            httpPost.setEntity(reqEntity);
			long begin = System.currentTimeMillis();
			System.out.println(new Date() +"发起请求的页面地址 " + httpPost.getRequestLine());
            // 发起请求 并返回请求的响应
            CloseableHttpResponse httpResponse = httpClient.execute(httpPost);
            try {
                System.out.println("----------------------------------------");
				System.out.println("上传结束,用时:" + (System.currentTimeMillis()-begin)+"ms");
                // 打印响应状态
                System.out.println(httpResponse.getStatusLine());
                // 获取响应对象
                HttpEntity resEntity = httpResponse.getEntity();
                if (resEntity != null) {
                    // 打印响应长度
                    System.out.println("Response content length: "+ resEntity.getContentLength());
                    // 打印响应内容
                   String json=EntityUtils.toString(resEntity,Charset.forName("UTF-8"));
                    System.out.println(json);
                }
                // 销毁
                EntityUtils.consume(resEntity);
            } finally {
            	httpResponse.close();
            }
        } finally {
            httpClient.close();
        }
	}
	@Test
	public void delete() throws Exception {
		CloseableHttpClient httpClient = HttpClients.createDefault();
		try {
			// 把一个普通参数和文件上传给下面这个地址 是一个servlet
			HttpPost httpPost = new HttpPost("http://filesys.hengchang6.com/fs-api/removeFile.hc");
			StringBody fsId = new StringBody("570CFCC84EF44B08B58EE70A08347984", ContentType.create("text/plain", Consts.UTF_8));
			//以浏览器兼容模式运行，防止文件名乱码。
			HttpEntity reqEntity = MultipartEntityBuilder.create().setMode(HttpMultipartMode.BROWSER_COMPATIBLE)
					.addPart("fsId", fsId).setCharset(CharsetUtils.get("UTF-8")).build();

			httpPost.setEntity(reqEntity);

			System.out.println("发起请求的页面地址 " + httpPost.getRequestLine());
			// 发起请求 并返回请求的响应
			CloseableHttpResponse httpResponse = httpClient.execute(httpPost);
			try {
				System.out.println("----------------------------------------");
				// 打印响应状态
				System.out.println(httpResponse.getStatusLine());
				// 获取响应对象
				HttpEntity resEntity = httpResponse.getEntity();
				if (resEntity != null) {
					// 打印响应长度
					System.out.println("Response content length: "+ resEntity.getContentLength());
					// 打印响应内容
					String json=EntityUtils.toString(resEntity,Charset.forName("UTF-8"));
					System.out.println(json);
				}
				// 销毁
				EntityUtils.consume(resEntity);
			} finally {
				httpResponse.close();
			}
		} finally {
			httpClient.close();
		}
	}
	@Test
	public void search() throws Exception {
    	CloseableHttpClient httpClient = HttpClients.createDefault();
        try {
            // 把一个普通参数和文件上传给下面这个地址 是一个servlet
            HttpPost httpPost = new HttpPost("http://192.168.100.70/fs-api/searchFile.hc");
            StringBody systemId = new StringBody("test", ContentType.create("text/plain", Consts.UTF_8));
            StringBody businessId = new StringBody("1001", ContentType.create("text/plain", Consts.UTF_8));
            //以浏览器兼容模式运行，防止文件名乱码。
            HttpEntity reqEntity = MultipartEntityBuilder.create().setMode(HttpMultipartMode.BROWSER_COMPATIBLE)
                    .addPart("systemId", systemId).addPart("businessId", businessId).setCharset(CharsetUtils.get("UTF-8")).build();

            httpPost.setEntity(reqEntity);

            System.out.println("发起请求的页面地址 " + httpPost.getRequestLine());
            // 发起请求 并返回请求的响应
            CloseableHttpResponse httpResponse = httpClient.execute(httpPost);
            try {
                System.out.println("----------------------------------------");
                // 打印响应状态
                System.out.println(httpResponse.getStatusLine());
                // 获取响应对象
                HttpEntity resEntity = httpResponse.getEntity();
                if (resEntity != null) {
                    // 打印响应长度
                    System.out.println("Response content length: "+ resEntity.getContentLength());
                    // 打印响应内容
                   String json=EntityUtils.toString(resEntity,Charset.forName("UTF-8"));
                    System.out.println(json);
                }
                // 销毁
                EntityUtils.consume(resEntity);
            } finally {
            	httpResponse.close();
            }
        } finally {
            httpClient.close();
        }
	}

	/**
	 * @Title: download
	 * @Description: 文件下载
	 * @param localPath 下载本地路径
	 * @param fsId 文件ID(成功上传文件返回的fsId)
	 * @return void
	 * @throws
	 */
	public void download(String localPath, String fsId) throws Exception {
		if (fsId == null || fsId.equals(""))
			throw new NullPointerException("文件路径不存在");
		String url = DOWNLOAD_PATH + "?fsId=" + fsId;
		CloseableHttpClient httpClient = HttpClients.createDefault();
		try {
			// 下载文件地址
			String filePath = localPath;
			HttpGet httpGet = new HttpGet(url);
			System.out.println("发起请求的页面地址 " + httpGet.getRequestLine());
			CloseableHttpResponse httpResponse = httpClient.execute(httpGet);
			try {
				System.out.println("----------------------------------------");
				System.out.println(httpResponse.getStatusLine());
				HttpEntity resEntity = httpResponse.getEntity();
				if (resEntity != null) {
					System.out.println("文件长度  : " + resEntity.getContentLength());
					InputStream is = resEntity.getContent();
					byte[] by = new byte[1024];
					int index = 0;
					FileOutputStream fos = new FileOutputStream(new File(filePath));
					while((index = is.read(by)) != -1) {
						fos.write(by, 0, index);
					}
					fos.flush();
					fos.close();
					is.close();
				}
				// 销毁
				EntityUtils.consume(resEntity);
			} finally {
				httpResponse.close();
			}
		} finally {
			httpClient.close();
		}
	}

	public static void main(String[] args) throws Exception {
//		NewTestUpload.getInstance().delete();
//		NewTestUpload.getInstance().search();
//		NewTestUpload.getInstance().upload();
//		NewTestUpload.getInstance().download("D:\\download.csv", "B7E95C26EC3F45E5B487FF36A49B4AF7");
		//NewTestUpload.getInstance().download("D:\\download.doc", "40A1222E81D34AA6BAE3A5111F6485A3");
	}

}
